package com.thermal.thermal_inspection.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.thermal.thermal_inspection.entity.Classes;
import com.thermal.thermal_inspection.entity.RealName;
import com.thermal.thermal_inspection.entity.User;
import com.thermal.thermal_inspection.mapper.ClassMapper;
import com.thermal.thermal_inspection.mapper.ClassUserMapper;
import com.thermal.thermal_inspection.mapper.RealNameMapper;
import com.thermal.thermal_inspection.mapper.UserMapper;
import com.thermal.thermal_inspection.service.AccountService;
import com.thermal.thermal_inspection.vo.ClassWorkerVO;
import com.thermal.thermal_inspection.vo.LoginRespVO;
import com.thermal.thermal_inspection.vo.UserInfoVO;
import com.thermal.thermal_inspection.vo.GetUserRespVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    ClassUserMapper classUserMapper;
    @Autowired
    RealNameMapper realNameMapper;
    @Autowired
    ClassMapper classMapper;

    private static final Logger logger = Logger.getLogger(AccountServiceImpl.class);

    /**
     * 判断用户是否存在
     */
    @Override
    public boolean existUser(int userId){
        return userMapper.getUserByUserId(userId) != null;
    }

    /**
     * 登录
     */
    @Override
    public LoginRespVO login(String username, String password){
        //先查找用户是否存在
        User user = userMapper.existUser(username, password);
        if(user == null){
            logger.error("用户名或密码错误");
            return null;
        }

        //用户存在，则返回SaTokenInfo

        int userId = userMapper.getUserIdByUsername(username);
        StpUtil.login(userId);
        logger.info("登录成功");
        SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();

        LoginRespVO loginRespVO = userMapper.getLoginRespVO(username);
        loginRespVO.setSaTokenInfo(saTokenInfo);

        return loginRespVO;
    }

    /**
     * 注册
     */
    @Override
    public int register(String username, String password, String realName, String email, String phone, int role){
        //先检查是否有重复(检查user表，username不能相同)
        User user = userMapper.getUserByUsername(username);
        if(user != null){
            logger.error("注册失败，该用户名已存在");
            return 0;
        }

        int rows1 = userMapper.register(username, password, email, role);
        int userId = userMapper.getUserIdByUsername(username);
        int rows2 = realNameMapper.register(userId, realName, phone);
        if(rows1 == 0 || rows2 == 0){
            logger.error("注册失败");
            return 0;
        }
        logger.info("注册成功");
        return 1;
    }

    /**
     * 删除工人
     */
    @Override
    public int deleteUser(int userId){
        //先判断工人是否存在
        User user = userMapper.getUserByUserId(userId);
        if(user == null){
            logger.error("删除失败，该用户不存在");
            return 0;
        }


        int rows1 = userMapper.deleteUser(userId);
        int rows2 = realNameMapper.deleteWorker(userId);
        int rows3 = classUserMapper.deleteUser(userId);
        if(rows1 == 0 || rows2 == 0){
            logger.error("删除失败");
            return 0;
        }
        logger.info("删除成功");
        return 1;
    }

    /**
     *查找所有工人
     */
    @Override
    public List<GetUserRespVO> getUsers() {
        logger.info("查找所有工人成功");
        return realNameMapper.getUsers();
    }

    /**
     * 修改信息
     */
    @Override
    public int fixAccount(int userId, String username, String realName, String email, String phone, int classId, int role){
        //先判断工人是否存在
        User user1 = userMapper.getUserByUserId(userId);
        if(user1 == null){
            logger.error("修改信息失败，该用户不存在");
            return 0;
        }

        //然后判断用户名是否已存在（除开自己）
        User user2 = userMapper.getUserByUsername(username);
        if(user2 != null && user1.getId() != user2.getId()){
            logger.error("修改信息失败，用户名已存在，请重新填写用户名");
            return 0;
        }

        int rows1 = userMapper.fix(userId, username, email, role);
        int rows2 = realNameMapper.fix(userId, realName, phone, classId);
        logger.info("classId:" + classId);
        int rows3 = classUserMapper.fix(userId, classId);
        if(rows1 == 0 || rows2 == 0){
            logger.error("修改信息失败");
            return 0;
        }

        logger.info("修改信息成功");
        return 1;
    }

    /**
     * 查找个人信息
     */
    @Override
    public UserInfoVO getUserInfo(int userId){
        //先判断工人是否存在
        User user1 = userMapper.getUserByUserId(userId);
        if(user1 == null){
            logger.error("查找信息失败，该工人不存在");
            return null;
        }

        logger.info("查找个人信息成功");
        return userMapper.getUserInfoByUserId(userId);
    }

    /**
     * 先验证身份，是工人还是管理员，管理员则无需验证身份，工人需要判断密码是否相同
     */
    @Override
    public int isOldPassword(int requestUserId, int userId, String oldPassword) {
        int role = userMapper.getRoleById(requestUserId);
        if (role == 3){
            if(userMapper.getUserByUserId(userId).getPassword().equals(oldPassword))
                //通过验证
                return 1;
            //未通过验证
            return 0;
        }
        //管理员直接通过验证
        return 1;
    }

    /**
     * 修改密码
     */
    @Override
    public int fixPassword(int userId, String newPassword){
        //先判断工人是否存在
        int rows = userMapper.fixPassword(userId, newPassword);
        if(rows == 0){
            logger.error("修改密码失败，人员不存在");
            return 0;
        }

        logger.info("修改密码成功");
        return rows;
    }

    /**
     * 搜索指定用户
     */
    @Override
    public List<RealName> getSpecifiedUser(Integer userId, String realName){
        return realNameMapper.getSpecifiedUser(userId, realName);
    }

    /**
     * 查询班组下所有用户
     */
    @Override
    public List<ClassWorkerVO> selectByClass(){
        List<ClassWorkerVO> classWorkerVOList = new ArrayList<>();
        List<Classes> classesList = classMapper.getClasses();
        for(Classes classes: classesList){
            ClassWorkerVO classWorkerVO = new ClassWorkerVO();
            classWorkerVO.setClassId(classes.getClassId());
            classWorkerVO.setClassName(classes.getClassName());
            List<RealName> realNameList = realNameMapper.getClassMembers(classes.getClassId());
            logger.info("realNameList:" + realNameList);
            List<ClassWorkerVO.Worker> workerList = new ArrayList<>();
            for(RealName realName: realNameList){
                ClassWorkerVO.Worker worker = new ClassWorkerVO.Worker();
                worker.setUserId(realName.getUserId());
                worker.setRealName(realName.getRealName());
                workerList.add(worker);
            }
            classWorkerVO.setWorkerList(workerList);
            classWorkerVOList.add(classWorkerVO);
        }
        return classWorkerVOList;
    }

    /**
     * 按照工人真实姓名查询工人
     */
    @Override
    public List<RealName> getUserByRealName(String realName){
        List<Integer> userIdList = realNameMapper.getUserIdByRealName(realName);
        List<RealName> userList = new ArrayList<>();
        for(int userId:userIdList){
            userList.add(realNameMapper.getRealNameByUserId(userId));
        }
        return userList;
    }
}
